package sqlexplorer.commands;

import java.io.IOException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.PlatformUI;
import org.json.simple.parser.ParseException;

import sqlexplorer.application.ConnectionsController;
import sqlexplorer.ui.views.CreateConnectionDialog;

public class ImportConnectionsHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		IViewReference [] iviews = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences();
		
		
		for(IViewReference viewReference : iviews) {
			if(viewReference.getId().equals("sqlexplorer.ui.views.queryview")) {
				Shell shell = viewReference.getView(true).getSite().getShell();
				FileDialog fileDialog = new FileDialog(shell);
				fileDialog.setFilterExtensions(new String[]{"*.json"});
				fileDialog.setFilterNames(new String[]{"JSON (*.json)"});
				String fileName = fileDialog.open();
				
				if(fileName != null) {
					try {
						ConnectionsController.getInstance().importConnections(fileName);
					} catch (IOException e) {
						MessageBox msgBox=new MessageBox(shell ,SWT.ICON_WARNING|SWT.OK);
						msgBox.setText("Warning");
						msgBox.setMessage("Import failed.");
						msgBox.open();
					} catch (ParseException e) {
						MessageBox msgBox=new MessageBox(shell ,SWT.ICON_WARNING|SWT.OK);
						msgBox.setText("Warning");
						msgBox.setMessage("Import failed.");
						msgBox.open();
					}
				}
			}
		}
		return null;
	}

}
